'use strict';
import React from "react";
import { Form, Input, Button, Spin, message } from 'antd';
const FormItem = Form.Item;

import { push, goBack } from 'react-router-redux';
import { connect } from 'react-redux';
import { hashHistory } from 'react-router';

import {changeUsername} from '../actions/RegForm';

import {reg} from '../services/User';

class RegForm extends React.Component{
  constructor(props) {
    super(props);
    this.state ={
      loading: false
    };

  }

  handleSubmit(e) {
     e.preventDefault();
     this.setState({loading: true});

      let userData = {
        username: this.props.form.getFieldsValue().username,
        password: this.props.form.getFieldsValue().password,
        email: this.props.form.getFieldsValue().email
      }

      reg(userData).then(
        user => this.handleSignUpSuccess(user),
        error => this.handleSignUpError(error)
      );
   }

   handleSignUpSuccess(user) {
     message.success('注册成功！立即登录');
     this.setState({loading: false});
     hashHistory.push("login");
   }
   handleSignUpError(error) {
     // Show the error message somewhere and let the user try again.
     message.error("Error: " + error.code + " " + error.message);
     this.setState({loading: false});
     this.props.form.setFieldsValue({
       email: '',
       password: '',
       username: ''
     });

   }

  render() {

     const { getFieldProps } = this.props.form;
     const { dispatch, regForm } = this.props;

    return (
      <Spin spinning={this.state.loading} size="small">
        <Spin spinning={this.state.loading} />
        <Spin spinning={this.state.loading} size="large" />
        <Form horizontal onSubmit={this.handleSubmit.bind(this)}>
        <FormItem
          label="邮箱"
        >
          <Input placeholder="请输入邮箱"
            {...getFieldProps('email')}
          />
        </FormItem>
         <FormItem
           label="密码"
         >
           <Input type="password" placeholder="请输入密码"
             {...getFieldProps('password')}
           />
         </FormItem>
         <FormItem
           label="账户"
         >
           <Input placeholder="请输入账户名"
             {...getFieldProps('username')}
           />
         </FormItem>

         <Button type="primary" htmlType="submit">注册</Button>
       </Form>
     </Spin>
    );
  }
}
function mapStateToProps(state) {
  return {
    regForm: state.RegForm
   };
}

RegForm = Form.create()(RegForm);
export default connect(mapStateToProps)(RegForm);
